package com.eshunda.eshunda_android_demo;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.eshunda.ldt.SdkManager;
import com.eshunda.ldt.bean.DetectResult;
import com.eshunda.ldt.bean.InitConfig;
import com.eshunda.ldt.biz.DetectCallback;
import com.google.android.material.button.MaterialButton;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 活体检测主界面 - 身份认证初始化页面
 * 默认使用眨眼检测（类型2）
 */
public class LivingActivity extends AppCompatActivity implements View.OnClickListener {
    
    // ==================== 常量定义 ====================
    private static final String TAG = "LivingActivity";
    private static final String CAMERA_ID = "1";
    private static final int THREAD_POOL_SIZE = 3;
    private static final int EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS = 5;
    
    // 活体检测类型编码 - 默认使用眨眼检测
    private static final int DETECT_TYPE_BLINK = 2;
    
    // ==================== UI 组件 ====================
    private ImageButton btnBack;
    private MaterialButton btnStartVerify;
    
    // ==================== 业务对象 ====================
    private SdkManager sdkManager;
    private HTTPClient httpClient;
    private ExecutorService executorService;
    
    // ==================== 状态管理 ====================
    private int livingType = DETECT_TYPE_BLINK; // 默认活体类型为2（眨眼检测）
    private String token;

    // ==================== 生命周期方法 ====================
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_living);
        
        initSdk();
        initViews();
        initExecutor();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        shutdownExecutor();
    }
    
    // ==================== 初始化方法 ====================
    
    /**
     * 初始化SDK
     * 注意：建议在Application中提前调用以提升性能
     */
    private void initSdk() {
        SdkManager.Init();
        SdkManager.cameraID = CAMERA_ID;
        
        // 打印SDK版本信息
        Log.d(TAG, "SDK版本: " + SdkManager.getVersion());
        
        httpClient = new HTTPClient();
        sdkManager = new SdkManager(this);
    }
    
    /**
     * 初始化视图组件
     */
    private void initViews() {
        // 初始化返回按钮
        btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(this);
        
        // 初始化开始认证按钮
        btnStartVerify = findViewById(R.id.btn_start_verify);
        btnStartVerify.setOnClickListener(this);
    }
    
    /**
     * 初始化线程池
     */
    private void initExecutor() {
        executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
            @Override
            public Thread newThread(@NonNull Runnable r) {
                return new Thread(r, "LivingDetection-Worker");
            }
        });
    }
    
    /**
     * 关闭线程池
     */
    private void shutdownExecutor() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down executor", e);
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    // ==================== 业务逻辑方法 ====================
    
    /**
     * 开始活体检测
     */
    private void startLivingDetect() {
        SdkManager.s_isOpenVideoRecorder = true;
        
        executorService.execute(() -> performLivingDetection());
    }
    
    /**
     * 执行活体检测流程
     */
    private void performLivingDetection() {
        try {
            // 1. 初始化检测配置（使用默认的眨眼检测类型2）
            InitConfig config = new InitConfig(livingType);
            DetectResult initResult = sdkManager.authInit(config);
            
            if (initResult == null || initResult.getData() == null) {
                Log.e(TAG, "SDK初始化失败");
                return;
            }
            
            // 2. 调用阿里云获取token
            String response = httpClient.authInit(initResult.getData());
            if (response == null || response.isEmpty()) {
                Log.e(TAG, "获取token失败：响应为空");
                return;
            }
            
            // 3. 解析token
            JSONObject responseJson = JSONObject.parseObject(response);
            String code = responseJson.getString("code");
            if(!"200".equals(code)){
                Log.e(TAG, "获取token失败：状态码为:" + code);
                return;
            }

            token = responseJson.getJSONObject("data").getString("token");
            if (token == null || token.isEmpty()) {
                Log.e(TAG, "获取token失败：token为空");
                return;
            }
            
            Log.d(TAG, "Token获取成功，开始活体检测，检测类型：" + livingType);
            // 4. 开始活体检测
            sdkManager.startLivingDetect(token, new DetectCallback() {
                @Override
                public void onFinish(final DetectResult result) {
                    handleDetectionResult(result);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "活体检测过程中发生错误", e);
        }
    }
    
    /**
     * 处理检测结果
     */
    private void handleDetectionResult(final DetectResult result) {
        if (result == null) {
            Log.e(TAG, "检测结果为空");
            return;
        }
        
        executorService.execute(() -> {
            try {
                String authResult = httpClient.auth(result);
                Log.d(TAG, "认证结果：" + authResult);
                // TODO: 处理认证结果
            } catch (Exception e) {
                Log.e(TAG, "处理检测结果时发生错误", e);
            }
        });
    }

    // ==================== 事件处理方法 ====================
    
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        
        if (viewId == R.id.btn_back) {
            // 返回上一页
            finish();
        } else if (viewId == R.id.btn_start_verify) {
            // 开始认证
            startLivingDetect();
        }
    }
}
